#include <string>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>

#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 

void msleep(unsigned int ms)
{
        int microseconds = ms * 1000;
        struct timeval tv;
        tv.tv_sec = microseconds / 1000000;
        tv.tv_usec = microseconds % 1000000;
        select(0, NULL, NULL, NULL, &tv);
}

int main(int argc, char *argv[])
{
        if (argc < 3) {
                std::cerr << "usage " << argv[0] << " host port" << std::endl;
                return 1;
        }

        // Creates new socket
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd < 0) {
                std::cerr << "Error opening socket" << std::endl;
                return 1;
        }
        hostent* server = gethostbyname(argv[1]);
        if (server == NULL) {
                std::cerr << "No such host" << std::endl;
                return 1;
        }

        sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        strcpy((char*)&serv_addr.sin_addr.s_addr, server->h_addr);
        int portno = atoi(argv[2]);
        serv_addr.sin_port = htons(portno);

        if(connect(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
                std::cerr << "ERROR connecting" << std::endl;
                return 1;
        }

        for(int i = 1; i <= 20; i++)
        {
                uint16_t x = htons(i);
                int n = write(sockfd, &x, sizeof(uint16_t));
                if(n < 0) {
                        std::cerr << "ERROR writing to socket" << std::endl;
                        return 1;
                }
                std::cout << i << std::endl;
                msleep(500);
        }

        close(sockfd);
        return 0;
}
